import React, { useState, useEffect } from 'react'
import { Button, Tag, message, notification, Modal, Input } from 'antd'
import { formatTime } from '../../../utils/time'
import { useSelector } from 'react-redux'
import { getAuditListInformation, patchAuditInformation } from '../../../utils/request/get'
import { updateRecordAuditStateById } from '../../../utils/request/put'
import MyTable from '../../../components/newsSandBox/MyTable'
import { copy } from '../../../utils/common'
import { useLocation } from 'react-router-dom'
import { getCache } from '../../../utils/cache'

export default function List() {
    const [dataSource, setDataSource] = useState([])
    const [showData, setShowData] = useState([])
    const [audits, setAudits] = useState([])
    const [header, setHeader] = useState([])
    const [categories, setCategories] = useState([])
    const [services, setServices] = useState([])
    const [total, setTotal] = useState(0)
    const [currentItem, setCurrentItem] = useState(null)
    const [suggestVisible, setSuggestVisible] = useState(false)
    const [suggestInput, setSuggestInput] = useState('')
    const token = useSelector(state => state.TokenReducer.token)
    const location = useLocation()
    const fontColor = ['rgb(239,185,27)', '#ff9912', 'rgb(0,134,132)']

    useEffect(() => {
        async function fetchData() {
            if (token) {
                const { list, audits, header, categories, services } = await getAuditListInformation(token)
                setAudits(audits)
                setHeader(header)
                setCategories(categories)
                setServices(services)
                if (location) {
                    const path = location.pathname
                    if (path === '/audit-manage/emergent') {
                        const data = getCache('emergent')
                        const emergents = await patchAuditInformation(data)
                        if (emergents === null) {
                            setTotal(0)
                            setDataSource([])
                            setShowData([])
                        } else {
                            setTotal(emergents.length)
                            setDataSource(emergents)
                            setShowData(emergents)
                        }

                    } else {
                        if (list) {
                            setTotal(list.length)
                            setDataSource(list)
                            setShowData(list)
                        }
                    }
                }
            }
        }
        fetchData()
    }, [token, location])

    const colors = ['warning', 'processing', 'success', 'error']
    const columns = [
        {
            title: header['categoryName'],
            dataIndex: 'categoryName',
            width: 90,
            fixed: 'left',
            onCell: record => ({
                onClick: () => {
                    copy(record.categoryName)
                }
            }),
            sorter: (a, b) => {
                // 按 id 升序排列
                return a.Category.id - b.Category.id
            },
            filters: [...categories.map(item => ({
                text: item.title, value: item.title,
            }))],
            onFilter: (value, record) => {
                return record.categoryName.indexOf(value) === 0
            },
            render: (categoryName) => {
                return <b>{categoryName}</b>
            }
        },
        {
            title: header['serviceName'],
            dataIndex: 'serviceName',
            width: 85,
            fixed: 'left',
            onCell: record => ({
                onClick: () => {
                    copy(record.serviceName)
                }
            }),
            filters: [...services.map(item => ({
                text: item.title, value: item.title,
            }))],
            onFilter: (value, record) => record.serviceName.indexOf(value) === 0
        },
        {
            title: header['unitName'],
            dataIndex: 'unitName',
            width: 70,
            onCell: record => ({
                onClick: () => {
                    copy(record.unitName)
                }
            }),
        },
        {
            title: header['code'],
            dataIndex: 'code',
            width: 60,
            onCell: record => ({
                onClick: () => {
                    copy(record.code)
                }
            }),
        },
        {
            title: header['customerName'],
            dataIndex: 'customerName',
            width: 60,
            onCell: record => ({
                onClick: () => {
                    copy(record.customerName)
                }
            }),
        },
        {
            title: header['identityId'],
            dataIndex: 'identityId',
            width: 70,
            onCell: record => ({
                onClick: () => {
                    copy(record.identityId)
                }
            }),
        },
        {
            title: header['username'],
            dataIndex: 'User',
            width: 50,
            onCell: record => ({
                onClick: () => {
                    copy(record.User.username)
                }
            }),
            render: (user) => {
                return user.username
            }
        },
        {
            title: header['acceptedTime'],
            dataIndex: 'acceptedTime',
            width: 60,
            onCell: record => ({
                onClick: () => {
                    copy(record.acceptedTime)
                }
            }),
            sorter: (a, b) => {
                return new Date(a.acceptedTime) - new Date(b.acceptedTime)
            },
            render: (time) => {
                return formatTime(time)
            }
        },
        {
            title: header['endTime'],
            dataIndex: 'endTime',
            width: 60,
            onCell: record => ({
                onClick: () => {
                    copy(record.endTime)
                }
            }),
            sorter: (a, b) => {
                return new Date(a.endTime) - new Date(b.endTime)
            },
            render: (time) => {
                return formatTime(time)
            }
        },
        {
            title: '审核人',
            dataIndex: 'auditUsername',
            width: 50,
            onCell: record => ({
                onClick: () => {
                    copy(record.auditUsername)
                }
            }),
            render: (auditUsername) => {
                return auditUsername ? auditUsername : <span style={{ color: fontColor[0] }}>暂未审核</span>
            }
        },
        {
            title: header['auditState'],
            dataIndex: 'auditState',
            width: 50,
            sorter: (a, b) => {
                // 按 id 升序排列
                return a.Audit.id - b.Audit.id
            },
            filters: [...audits.map(item => ({
                text: item.title, value: item.title,
            }))],
            onFilter: (value, record) => {
                return record.auditState.indexOf(value) === 0
            },
            render: (auditState) => {
                return <Tag color={getColor(auditState)}>{auditState}</Tag>
            }
        },
        {
            title: header['auditSuggest'],
            dataIndex: 'auditSuggest',
            width: 70,
            onCell: record => ({
                onClick: () => {
                    copy(record.auditSuggest)
                }
            }),
            render: (auditSuggest) => {
                return auditSuggest
            }
        },
        {
            title: '操作',
            width: 60,
            render: (record) => {
                switch (record.Audit.id) {
                    case 1:
                        return <Button
                            type="primary"
                            style={{ backgroundColor: fontColor[1], color: 'white', borderColor: fontColor[1] }}
                            onClick={() => { handleClick(record, 2) }}>提交</Button>
                    case 2:
                        return <Button
                            type="primary" danger
                            onClick={() => { handleClick(record, 3) }}>通过</Button>
                    case 3:
                        return <Button
                            type="primary"
                            onClick={() => { handleClick(record, 4) }}>修改</Button>
                    case 4:
                        return <Button
                            type="primary"
                            style={{ backgroundColor: fontColor[2], color: 'white', borderColor: fontColor[2] }}
                            onClick={() => { handleClick(record, 1) }}>申请</Button>
                    default:
                        return <Button
                            type="primary"
                            onClick={() => { }}></Button>
                }
            }
        }
    ]

    const getColor = (item) => {
        const { id } = audits.find(x => x.title === item)
        return colors[id]
    }

    const handleTableChange = (pagination, filters, sorter, extra) => {
        let showDatas = dataSource;

        // 遍历 filters 对象中的所有属性
        Object.keys(filters).forEach(filterKey => {
            const filterValues = filters[filterKey];

            if (filterValues && filterValues.length > 0) {
                showDatas = showDatas.filter(item => {
                    // 使用 indexOf 判断是否包含筛选条件
                    return filterValues.some(value => item[filterKey].indexOf(value) === 0);
                });
            }
        });

        // 更新显示数据和总数
        setShowData(showDatas);
        setTotal(showDatas.length);
    }

    const handleOk = async () => {
        if (!suggestInput) {
            message.error('请输入修改意见')
            return
        }
        setSuggestVisible(false)
        const { item, type } = currentItem
        if (item && type) {
            const res = await update(item, type)
            if (res) {
                switch (type) {
                    case 1:
                        handleNotification(item, "提交申请") // 未通过 => 未审核
                        break
                    case 2:
                        handleNotification(item, "提交") // 未审核 => 审核中
                        break
                    case 3:
                        handleNotification(item, "通过") // 审核中 => 已通过
                        break
                    case 4:
                        handleNotification(item, "修改为未通过") // 已通过 => 未通过
                        break
                    default:
                        break
                }
            } else {
                message.info('修改失败')
            }
        }
    }

    const update = async (item, toState) => {
        const auditUserId = token.userId
        const auditUsername = token.username
        const auditSuggest = suggestInput
        setShowData(showData.map(value => {
            if (item.id === value.id) {
                return {
                    ...value,
                    auditId: toState,
                    auditState: audits[toState - 1].title,
                    auditUsername,
                    auditSuggest,
                    Audit: audits[toState - 1]
                }
            }
            return value
        }))
        // console.log(item);
        setSuggestInput('')
        return await updateRecordAuditStateById(item.id, { auditId: toState, auditUserId, auditSuggest })
    }

    const handleNotification = (item, stateMessage) => {
        notification.info({
            message: '审核通知',
            description: <>由
                <span style={{ color: 'red' }}>{item.User.username}</span>
                办理的业务已
                <span style={{ color: 'blue' }}>{stateMessage}</span>
                审核</>,
            placement: 'bottomRight'
        })
    }

    const handleClick = (item, type) => {
        setSuggestVisible(true)
        setCurrentItem({ item, type })
    }

    return (
        <>
            <MyTable
                total={total}
                pageSize={10}
                columns={columns}
                dataSource={showData}
                onChange={handleTableChange}
                params={{
                    size: 'middle',
                    bordered: true,
                    rowClassName: { textAlign: 'center' },
                    scroll: {
                        x: 2400,
                        y: 460,
                    }
                }}
            />
            <Modal
                open={suggestVisible}
                title={"请提交修改意见"}
                okText='确认'
                cancelText="取消"
                onCancel={() => setSuggestVisible(false)}
                onOk={() => handleOk()}
            >
                <Input.TextArea placeholder='请输入修改意见' value={suggestInput} onChange={(e) => setSuggestInput(e.target.value)} />
            </Modal>
        </>
    )
}